package com.enjoyor.soa.traffic.frame.interceptor;

import com.enjoyor.soa.traffic.util.exception.NoServiceException;
import com.enjoyor.soa.traffic.util.helper.LoggerHelper;
import com.enjoyor.soa.traffic.util.helper.ResultHelper;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Aspect
@Component
public class ManagerInterceptor {

    private static final Logger logger = Logger.getLogger(ManagerInterceptor.class);
    private String methodInfo;
    private long startTime;
    private long endTime;

    @Pointcut("(execution(public * com.enjoyor.soa.traffic.web.**.service..*(..)))")
    public void executeMethodPointcut() {
    }

    @Around("executeMethodPointcut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) {
        Object object = null;
        try {
            object = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            Field[] realFields = proceedingJoinPoint.getTarget().getClass().getDeclaredFields();
            for (Field field : realFields) {
                field.setAccessible(true);
                Object value = field.get(proceedingJoinPoint.getTarget());
                if (value == null) {
                    MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
                    Method method = signature.getMethod();
                    String methodName = method.getName();
                    String message = "无法获取名称为【" + field.getGenericType() + "】的DUBBO服务,检查对应服务是否开启，或者服务是否有获取限制。";
                    String errorContext = field.getGenericType() + "服务出错";
                    LoggerHelper.writeErrorLogInfo(errorContext, this.getClass().getSimpleName(), methodName, null, new NoServiceException(message));
                }
            }
            object = ResultHelper.getResult((Exception) throwable);
        } finally {
            return object;
        }
    }
}
